import {  Card, List, message } from "antd";
import { useEffect, useState } from "react";
import { getTableApi, getToken } from "./utils/client";
import s from "./common.module.less";
import classNames from "classnames";

export interface TableListProps {
    curClientId: string;
    curDatabase: string;
    onChange: (table: string) => void;
}

function TableList(props: TableListProps) {
    const [tableList, setTableList] = useState<string[]>([]);
    const [curTable, setCurTable] = useState("");

    const loadTableList = async () => {
        setTableList([]);
        setCurTable("");
        const client = getTableApi();
        try {
            const res = await client.tableListPost({
                tableListPostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    db: props.curDatabase,
                },
            });
            setTableList(res);
        } catch (e) {
            console.log(e);
            message.error("无法列出数据表");
        }
    };

    useEffect(() => {
        if (props.curClientId !== "" && props.curDatabase !== "") {
            loadTableList();
        } else {
            setTableList([]);
            setCurTable("");
        }
    }, [props.curClientId, props.curDatabase]);

    useEffect(() => {
        props.onChange(curTable);
    }, [curTable]);

    return (
        <Card title="数据表列表" bodyStyle={{ height: "calc(100vh - 60px)", overflowY: "auto", overflowX: "hidden" }}>
            <List bordered={false} dataSource={tableList} renderItem={item => (
                <List.Item key={item} className={classNames(s.item, curTable == item ? s.active : "")} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    setCurTable(item);
                }}>
                    <div className={s.name} title={item}>{item}</div>
                </List.Item>
            )} />
        </Card>
    );
}

export default TableList;
